import datetime

from django.db.models import *
from django.utils import timezone

import question.models
import submission.models


def get_dict(obj, fields=None, exclude=None):
    data = {}
    for f in obj._meta.concrete_fields + obj._meta.many_to_many:
        value = f.value_from_object(obj)
        if fields and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        if isinstance(f, ManyToManyField):
            continue
        if isinstance(f, DateTimeField):
            value = value.strftime('%Y-%m-%d %H:%M:%S') if value else None
        elif isinstance(f, DateField):
            value = value.strftime('%Y-%m-%d') if value else None
        elif isinstance(f, TimeField):
            value = value.strftime('%H:%M:%S') if value else None
        data[f.name] = value
    return data


def saveAllSubmissions(Qusetionnaire):
    submissions = submission.models.Submission.objects.filter(questionnaireTo=Qusetionnaire)
    for sub in submissions:
        sub.isSubmitted = True
        sub.save()
        if Questionnaire.Settings.AnswerTime is not None and Questionnaire.Settings.DeadLine is not None:
            if Qusetionnaire.Settings.AnswerTime < (
                    Qusetionnaire.Settings.DeadLine - sub.createTime).seconds:
                sub.update(submitTime=sub.createTime + datetime.timedelta(seconds=Qusetionnaire.Settings.AnswerTime))
            else:
                sub.update(submitTime=Qusetionnaire.Settings.DeadLine)


def checkQuestionnaireTime(q):
    if q.Settings.StartTime and timezone.now().__gt__(q.Settings.StartTime):
        q.ReleaseTime = q.Settings.StartTime
        q.Open = True
        q.save()
        q.Settings.StartTime = None
        q.Settings.save()
    if q.Settings.DeadLine and timezone.now().__gt__(q.Settings.DeadLine):
        q.Open = False
        q.save()
        q.Settings.DeadLine = None
        q.Settings.save()
        saveAllSubmissions(q)


def checkAnswer(sub):
    answers = submission.models.Answer.objects.filter(submissionTo=sub)
    for answer in answers:
        quest = answer.questionTo
        if quest.Type == 10:
            trueChoices = question.models.Choice.objects.filter(Question=quest, IsTrueAnswer=True)
            tclist = []
            aslist = []
            for trueChoice in trueChoices:
                tclist.append(trueChoice.id)
            tclist.sort()
            answerchoices = answer.answerChoices.all()
            for answerchoice in answerchoices:
                tclist.append(answerchoice.id)
            aslist.sort()
            if tclist == aslist:
                answer.gradeStatus = 2
                answer.save()
            else:
                answer.gradeStatus = 0
                answer.save()
        elif quest.Type == 11:
            trueChoices = question.models.Choice.objects.filter(Question=quest, IsTrueAnswer=True)
            tclist = []
            aslist = []
            for trueChoice in trueChoices:
                tclist.append(trueChoice.id)
            tclist.sort()
            answerchoices = answer.answerChoices.all()
            for answerchoice in answerchoices:
                tclist.append(answerchoice.id)
            aslist.sort()
            if tclist == aslist:
                answer.gradeStatus = 2
                answer.save()
            elif set(tclist) > set(aslist):
                answer.gradeStatus = 1
                answer.save()
            else:
                answer.gradeStatus = 0
                answer.save()
        elif quest.Type == 13:
            answer.gradeStatus = 3
            answer.save()
